import { BaseStrategy } from './BaseStrategy.js';
import { delay, ensurePageOpen } from '../utils.js';
import { wuliu_rule } from '../rules/wuliu.js';
import { closePopups } from '../utils.js';
import path, { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { logInfo, logWarn, logError } from '../logger.js';
import fs from 'fs';
import statisticsService from '../services/statistics.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export class AlibabaStrategy extends BaseStrategy {
  constructor(context, config, jsonFileName) {
    super(context, config);
    this.jsonFileName = jsonFileName;
    this.baseUrl = config.baseUrl;
  }
  async processRefunds(accountKey, shopName = '') {
    logInfo(`[AlibabaStrategy] 开始处理${shopName || '未知店铺'}的退款订单`);
    let refundRecords = [];
    try {
      const page = await ensurePageOpen(this.context, this.baseUrl + '/home.htm/trade-platform/refund-list');
      this.pageLoad(page);
      logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}浏览器已启动`);
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(5000);
      await closePopups(page);
      try {
        const next = await page.waitForSelector('.driver-popover-next-btn', { timeout: 2000 });
        await next.click();
        logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}点击了下一步按钮`);
        const close = await page.waitForSelector('.driver-popover-close-btn', { timeout: 2000 });
        await close.click();
      } catch (error) {
        logWarn(`[AlibabaStrategy] ${shopName || '未知店铺'}没有找到下一步按钮`);
      }
      const dcl = await page.locator('div[class*="data-board_new_delivery_block"]').filter({ hasText: '待商家处理' }).locator('span').first();
      let text = await dcl.textContent() * 1;
      logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}待处理订单数量：${text}`);
      if (text == 0) {
        logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}没有待处理订单`);
        return;
      }
      await dcl.click();
      await page.waitForTimeout(2000);
      while (text > 0) {
        let zjsq = page.getByRole('button', { name: '最近申请排序 ' });
        if (await zjsq.isVisible()) {
          await zjsq.hover();
        } else {
          await page.getByRole('button', { name: '临近超时排序' }).hover({ timeout: 1000 }).catch(() => { });
        }
        const ljcs = page.getByRole('option', { name: '临近超时排序' }).locator('div');
        await ljcs.click();
        await page.waitForTimeout(5000);
        const hasnext = await this.processRefundItems(page, refundRecords, shopName);
        if (!hasnext) {
          break;
        }
      }
      // 保存所有退款成功数据
      if (accountKey && refundRecords.length > 0) {
        statisticsService.saveRefundRecord(accountKey, refundRecords);
      }
      logInfo('[AlibabaStrategy] 退款任务执行完成');
    } catch (err) {
      logError(`[AlibabaStrategy] 退款任务异常: ${err.stack || err}`);
    }
  }

  async processRefundItems(page, refundRecords = [], shopName = '') {
    logInfo(`[AlibabaStrategy] 开始处理${shopName || '未知店铺'}的退款订单列表`);
    let refundCount = 0;
    const items = page.locator('table.next-table-row');
    const count = await items.count();
    logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}订单数量：${count}`);
    for (let i = 0; i < count; i++) {
      const item = items.nth(i);
      const lookDetail = await item.getByText('查看详情', { timeout: 1000 })

      const isVisible = await lookDetail.isVisible();

      const refundStateDom = await item.getByText('买家退货', { timeout: 1000 })
      const refundStateVisible = await refundStateDom.isVisible();

      let refundState = false;
      if (!refundStateVisible) {
        const refundStateText = await refundStateDom.textContent();
        logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}订单状态：${refundStateText}`);
        if (!refundStateText.includes('已签收')) {
          logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}订单状态不是已签收，跳过`);
          continue;
        }
        refundState = true;
      }

      if (isVisible) {
        const newPagePromise = this.context.waitForEvent('page');
        await lookDetail.click();
        const detailPage = await newPagePromise;
        const itemData = await this.processDetail(detailPage, refundState, shopName);
        if (itemData) {
          logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}追加数据：${JSON.stringify(itemData)}`);
          refundCount++;
          // 处理每个退款成功订单时，push 到 refundRecords
          refundRecords.push(itemData);
        }
      }
    }
    // fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
    // logInfo('[AlibabaStrategy] 已保存到 ' + filePath);
    return refundCount > 5;
  }

  async processDetail(detailPage, refundState, shopName = '') {
    logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}进入订单详情页`);
    try {
      await detailPage.waitForLoadState();
      await detailPage.waitForTimeout(2000);
      await detailPage.getByRole('button', { name: '关闭' }).click({ timeout: 1000 }).catch(() => { });
      await closePopups(detailPage);
      const refund = await detailPage.locator('div[class*="refundinfo_refund-refundinfo-item"]').filter({ hasText: '要求:' }).locator('span').first();
      const refundText = await refund.textContent();
      logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}退款要求：${refundText}`);
      if (refundText === '退款') {
        logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}退款订单`);
        await detailPage.getByText('拦截快递').click({ timeout: 1000 }).catch(() => { logWarn(`[AlibabaStrategy] ${shopName || '未知店铺'}未找到拦截快递按钮`); });
      }
      if (refundText !== '退货退款') {
        logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}非退货退款订单，跳过`);
        await detailPage.close();
        return false;
      }
      const look = await detailPage.locator('div[class*="refundinfo_refund-dealinfo-item-label"]').getByText('查看');
      await look.hover();
      await detailPage.waitForTimeout(1500);
      const refundinfo = await detailPage.locator('div[class*="refundinfo_refund-dealinfo-logcontent-item"]  ol').first();
      const refundTextContent = await refundinfo.locator('li .next-step-item-title').allTextContents();
      let wuliulist = refundTextContent;
      if (Array.isArray(refundTextContent[0])) {
        wuliulist = refundTextContent[0];
      }
      const result = await wuliu_rule(wuliulist);
      if (!result) {
        if (refundState) {

          const orderId = await detailPage.locator('div[class*="dealinfo_refund-dealinfo-item"]').filter({ hasText: '订单编号' }).locator('a')
            .first().textContent().catch(() => { });
          const refundId = await detailPage.locator('div[class*="refundinfo_refund-refundinfo-item"]').filter({ hasText: '退款编号' }).locator('span').first().textContent().catch(() => { });

          logInfo(`[AlibabaStrategy] ${shopName || '未知店铺'}订单已签收，但未命中签收规则,订单ID：${orderId},退款ID：${refundId}`);

          this.sendNotification(shopName, orderId, refundId);
        }
        await detailPage.close();
        return false;
      }
      await refund.click();
      await detailPage.waitForTimeout(500);
      const remark = await detailPage.getByRole('button', { name: '备注' });
      remark.click();
      await detailPage.waitForTimeout(1000);
      const remarkInput = detailPage.getByRole('textbox', { name: '请输入备注内容' });
      const currentText = await remarkInput.inputValue().catch(() => '');
      if (currentText) {
        await remarkInput.fill(currentText + ';bot');
      } else {
        await remarkInput.fill('bot');
      }
      await detailPage.waitForTimeout(500);
      await detailPage.getByRole('button', { name: '确定' }).click();
      await detailPage.waitForLoadState('networkidle').catch(() => { });
      await detailPage.waitForTimeout(3000);
      await detailPage.getByRole('button', { name: '确认收货, 同意退款' }).click();
      await detailPage.waitForLoadState('networkidle').catch(() => { });
      await detailPage.waitForTimeout(2000);
      await detailPage.getByRole('button', { name: '同意退款', exact: true }).click();
      await detailPage.waitForLoadState('networkidle').catch(() => { });
      await detailPage.waitForTimeout(2000);
      const itemInfo = {
        '订单编号': await detailPage.locator('div[class*="dealinfo_refund-dealinfo-item"]').filter({ hasText: '订单编号' }).locator('a')
          .first().textContent().catch(() => { }),
        '退款编号': await detailPage.locator('div[class*="refundinfo_refund-refundinfo-item"]').filter({ hasText: '退款编号' }).locator('span').first().textContent().catch(() => { }),
        '售后时间': new Date().toLocaleString(),
      };
      await detailPage.close();
      logInfo(`[AlibabaStrategy] 完成订单详情处理: ${JSON.stringify(itemInfo)}`);
      return itemInfo;
    } catch (err) {
      logError(`[AlibabaStrategy] 订单详情处理异常: ${err.stack || err}`);
      await detailPage.close();
      return false;
    }
  }

  async getShipmentInfo(shopName = '店铺') {
    const page = await ensurePageOpen(this.context, this.baseUrl + '/home.htm/package-center/packageMonitor');
    console.log('浏览器已启动');
    this.pageLoad(page);
    await page.waitForLoadState('networkidle').catch(() => { });
    await closePopups(page);
    const lsyc = await page.getByText('揽收异常');
    await lsyc.click();

    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(5000);

    const xjfh = await page.getByText('即将虚假发货').locator('span').first().textContent()
      .catch(() => { });
    console.log('即将虚假发货：', xjfh);
    const ycfh = await page.getByText('延迟发货').locator('span').first().textContent()
      .catch(() => { });
    console.log('延迟发货：', ycfh);

    const hjfh = await page.getByText('虚假点击发货').locator('span').first().textContent()
      .catch(() => { });
    console.log('虚假发货：', hjfh);

    return {
      '店铺名称': shopName,
      '即将虚假发货': xjfh,
      '延迟发货': ycfh,
      '虚假发货': hjfh
    };
  }

  async getExchangePendingCount(shopName = '店铺') {
    const page = await ensurePageOpen(this.context, this.baseUrl + '/home.htm/trade-platform/refund-list');
    await page.waitForTimeout(3000);
    await closePopups(page);
    await page.getByRole('tab', { name: '换货', exact: true }).locator('div').click();
    await page.waitForTimeout(3000);
    await page.locator('span').filter({ hasText: '进行中的订单' }).nth(2).click();
    await page.waitForTimeout(500);
    await page.getByRole('option', { name: '待商家收货' }).locator('div').click();
    await page.waitForTimeout(3000);
    const items = page.locator('table.next-table-row');

    let count = 0;
    try {
      count = await items.count();
    } catch (e) {
      logWarn(`[${shopName}] 获取换货待处理订单数失败`);
    }
    logInfo(`[${shopName}] 换货待处理订单数: ${count}`);
    return { shopName, count };
  }

  async test() {
    const page = await ensurePageOpen(this.context, this.baseUrl + '/home.htm/trade-platform/refund-list');
    this.pageLoad(page);
    await page.pause();
  }


}
